from datetime import datetime, timezone
from enum import Enum
from pydantic import BaseModel, Field, field_validator, ConfigDict
from bson import ObjectId
from app.models.base import PyObjectId
# from typing import Final

class ModuleType(str, Enum):
    """模块类型枚举"""
    PROJECT = "project"          # 项目
    REQUIREMENT = "requirement"  # 需求
    TASK = "task"               # 任务
    DEFECT = "defect"           # 缺陷
    VERSION = "version"         # 版本
    DOCUMENT = "document"       # 文档
    USER = "user"               # 用户
    COMMENT = "comment"         # 评论
    NOTIFICATION = "notification" # 通知
    PROJECT_PRIORITY = "project_priority"  # 项目优先级
    REQUIREMENT_PRIORITY = "requirement_priority"  # 需求优先级
    DEFECT_PRIORITY = "defect_priority"    # 缺陷优先级
    TASK_PRIORITY = "task_priority"      # 任务优先级
    TEST_CASE = "test_case"     # 测试用例
    TEST_PLAN = "test_plan"     # 测试计划
    APPROVAL = "approval"       # 审批


class StateBase(BaseModel):
    """状态基础模型"""
    name: str = Field(..., min_length=1, max_length=100, description="状态名称")
    code: str = Field(..., min_length=1, max_length=50, description="状态代码")
    module_type: ModuleType = Field(..., description="模块类型")
    description: str | None = Field(None, max_length=2000, description="状态描述")
    color: str | None = Field(None, max_length=20, description="状态颜色")
    icon: str | None = Field(None, max_length=50, description="状态图标")
    sort_order: int = Field(default=0, description="排序顺序")
    is_enabled: bool = Field(default=True, description="是否启用")
    is_visible: bool = Field(default=True, description="是否可见")
    is_default: bool = Field(default=False, description="是否为默认状态")
    
    @field_validator('code')
    @classmethod
    def validate_code(cls, v: str) -> str:
        """验证状态代码格式"""
        if not v.replace('_', '').replace('-', '').isalnum():
            raise ValueError('状态代码只能包含字母、数字、下划线和连字符')
        return v.upper()


class StateCreate(StateBase):
    """创建状态模型"""
    pass


class StateUpdate(BaseModel):
    """更新状态模型"""
    name: str | None = Field(None, min_length=1, max_length=100, description="状态名称")
    description: str | None = Field(None, max_length=2000, description="状态描述")
    color: str | None = Field(None, max_length=20, description="状态颜色")
    icon: str | None = Field(None, max_length=50, description="状态图标")
    sort_order: int | None = Field(None, description="排序顺序")
    is_enabled: bool | None = Field(None, description="是否启用")
    is_visible: bool | None = Field(None, description="是否可见")
    is_default: bool | None = Field(None, description="是否为默认状态")


class StateInDB(StateBase):
    """数据库中的状态模型"""
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="创建时间")
    updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="更新时间")
  
    model_config = ConfigDict(
        populate_by_name=True,
        arbitrary_types_allowed=True,
        json_encoders={ObjectId: str}
    )


class State(StateInDB):
    """状态模型"""
    pass


class StateResponse(BaseModel):
    """状态响应模型"""
    id: str = Field(..., description="状态ID")
    name: str = Field(..., description="状态名称")
    code: str = Field(..., description="状态代码")
    module_type: ModuleType = Field(..., description="模块类型")
    description: str | None = Field(None, description="状态描述")
    color: str | None = Field(None, description="状态颜色")
    icon: str | None = Field(None, description="状态图标")
    sort_order: int = Field(..., description="排序顺序")
    is_enabled: bool = Field(..., description="是否启用")
    is_visible: bool = Field(..., description="是否可见")
    is_default: bool = Field(..., description="是否为默认状态")
    created_at: datetime | None = Field(None, description="创建时间")
    updated_at: datetime | None = Field(None, description="更新时间")


class ModuleStateResponse(BaseModel):
    """模块状态响应模型"""
    module_type: ModuleType = Field(..., description="模块类型")
    states: list[StateResponse] = Field(default_factory=list, description="状态列表")